package com.shengyuan.manage_os.old.ying.erpm.controls;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.shengyuan.manage_os.old.ying.erpm.MainApplication;
import com.shengyuan.manage_os.R;
import com.shengyuan.manage_os.old.ying.erpm.util.Utility;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


public class RecordButton extends LinearLayout implements OnClickListener {
	public static String VoiceFileName;
	private static final int MIN_INTERVAL_TIME = 1000;
	private long startTime;
	private Dialog recordIndicator;
	public String FILENAME = "voice.amr";
	
	private static int[] res = { R.drawable.mic_2, R.drawable.mic_3,
			R.drawable.mic_4, R.drawable.mic_5 };

	private static ImageView view;

	private MediaRecorder recorder;

	private ObtainDecibelThread thread;

	private Handler volumeHandler;

	public final static int MAX_TIME = 60;
	
	private LayoutParams PlayerBtnLayoutParams,DeleteBtnLayoutParams,TitleLayoutParams;
	public Button player, delete;
	public TextView title;
	private final int ID_PLAYER = 1,  ID_DELETE = 2, ID_TITLE = 3;
	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case ID_PLAYER:
			try {
				File amrFile = new File(VoiceFileName);
				if (amrFile!=null) {
					MediaPlayer mPlayer = new MediaPlayer();
					FileInputStream fis = new FileInputStream(amrFile);
					mPlayer.reset();
					mPlayer.setDataSource(fis.getFD());
					mPlayer.prepare();
					mPlayer.setLooping(false);
					mPlayer.start();
				}				
			} catch (Exception e) {
			}
			return;
		case ID_DELETE:
			Utility.delFile(VoiceFileName);
			title.setText("");
			break;
		}
	}

	public static boolean IsExist() {
		File file = new File(VoiceFileName);
		return file.exists();
	}
	
	public RecordButton(Context context) {
		super(context);
		init(context);
	}

	public RecordButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public void setSavePath(String path) {
		VoiceFileName = path;
	}
	
	public String getFileName()
	{
		String f= MainApplication.voicePath + FILENAME;
		File file = new File(f);
		if (file.exists()) {
			title.setText("已经录音");
		}else{
			title.setText("");
			title.setHint("长按录音");
			
		}
		return f;
	}

	private void init(Context context) {
		volumeHandler = new ShowVolumeHandler();
		player = new Button(context);
		delete = new Button(context);
		title = new TextView(context);
		player.setId(ID_PLAYER);
		delete.setId(ID_DELETE);
		title.setId(ID_TITLE);
		PlayerBtnLayoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.MATCH_PARENT);
		DeleteBtnLayoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.MATCH_PARENT);
		TitleLayoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.MATCH_PARENT);
		DeleteBtnLayoutParams.weight =  PlayerBtnLayoutParams.weight = 1;
		TitleLayoutParams.weight= 5;
		
		addView(title, TitleLayoutParams);
		addView(player , PlayerBtnLayoutParams);
		addView(delete, DeleteBtnLayoutParams);
		title.setText("");
		title.setTextSize(18.0f);
		title.setTextColor(Color.BLUE);
		title.setEllipsize(TruncateAt.MIDDLE);  
		title.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);  
		title.setSingleLine(true);  
		player.setText("播放");
		delete.setText("删除");
		
		player.setOnClickListener(this);
		delete.setOnClickListener(this);
		VoiceFileName = getFileName();
	}

	@Override
	public void postInvalidate() {
		super.postInvalidate();
		getFileName();
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {

		if (VoiceFileName == null)
			return false;

		int action = event.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			title.setText("正 在 录音");
			initDialogAndStartRecord();

			break;
		case MotionEvent.ACTION_UP:
			finishRecord();
			break;
		case MotionEvent.ACTION_CANCEL:
			cancelRecord();
			break;
		}

		return true;
	}

	private void initDialogAndStartRecord() {

		startTime = System.currentTimeMillis();
		recordIndicator = new Dialog(getContext(),
				R.style.like_toast_dialog_style);
		view = new ImageView(getContext());
		view.setImageResource(R.drawable.mic_2);
		recordIndicator.setContentView(view, new LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT));
		recordIndicator.setOnDismissListener(onDismiss);
		android.view.WindowManager.LayoutParams lp = recordIndicator
				.getWindow().getAttributes();
		lp.gravity = Gravity.CENTER;

		startRecording();
		recordIndicator.show();
	}

	private void finishRecord() {
		stopRecording();
		recordIndicator.dismiss();

		long intervalTime = System.currentTimeMillis() - startTime;
		if (intervalTime >= MIN_INTERVAL_TIME) {
			title.setText("录音已保存");
		} else {
			title.setText("请重新录音");
			Utility.delAllFile(MainApplication.voicePath);
		}
	}

	private void cancelRecord() {
		stopRecording();
		recordIndicator.dismiss();
		Utility.MessageBox(getContext(),"取消录音");
		Utility.delFile(VoiceFileName);
	}

	private void startRecording() {
		recorder = new MediaRecorder();
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setAudioChannels(1);
		recorder.setAudioEncodingBitRate(4000);
		recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		// recorder.setVideoFrameRate(4000);

		recorder.setOutputFile(VoiceFileName);

		try {
			recorder.prepare();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		recorder.start();
		thread = new ObtainDecibelThread();
		thread.start();

	}

	private void stopRecording() {
		if (thread != null) {
			thread.exit();
			thread = null;
		}
		if (recorder != null) {
			recorder.stop();
			recorder.release();
			recorder = null;
		}
	}

	private class ObtainDecibelThread extends Thread {

		private volatile boolean running = true;

		public void exit() {
			running = false;
		}

		@Override
		public void run() {
			while (running) {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if (recorder == null || !running) {
					break;
				}
				int x = recorder.getMaxAmplitude();
				if (x != 0) {
					int f = (int) (10 * Math.log(x) / Math.log(10));
					if (f < 26)
						volumeHandler.sendEmptyMessage(0);
					else if (f < 32)
						volumeHandler.sendEmptyMessage(1);
					else if (f < 38)
						volumeHandler.sendEmptyMessage(2);
					else
						volumeHandler.sendEmptyMessage(3);

				}

			}
		}

	}

	private OnDismissListener onDismiss = new OnDismissListener() {

		@Override
		public void onDismiss(DialogInterface dialog) {
			stopRecording();
		}
	};

	static class ShowVolumeHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			view.setImageResource(res[msg.what]);
		}
	}


}
